package com.iteaj.iot.test.modbus.dtu;

import com.iteaj.iot.AbstractProtocol;
import com.iteaj.iot.client.ClientConnectProperties;
import com.iteaj.iot.client.TcpSocketClient;
import com.iteaj.iot.modbus.client.ModbusTcpClient;
import com.iteaj.iot.modbus.client.ModbusTcpClientComponent;
import com.iteaj.iot.test.ClientSnGen;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;

import java.nio.charset.StandardCharsets;

public class ModbusDtuClientTestComponent extends ModbusTcpClientComponent<ModbusDtuClientTestMessage> {

    public ModbusDtuClientTestComponent(ClientConnectProperties config) {
        super(config);
    }

    @Override
    public String getName() {
        return "ModbusTcpClientForDtu";
    }

    @Override
    public TcpSocketClient createNewClient(ClientConnectProperties config) {
        String deviceSn = ClientSnGen.getClientSn() + "";

        return new ModbusTcpClient(this, config) {

            @Override
            protected void successCallback(ChannelFuture future) {

                // 第一包报文必须是设备编号
                getChannel().writeAndFlush(Unpooled.wrappedBuffer(deviceSn.getBytes(StandardCharsets.UTF_8)));
            }
        };
    }

    @Override
    public AbstractProtocol getProtocol(ModbusDtuClientTestMessage message) {
        return new ModbusDtuClientTestProtocol(message);
    }
}
